package com.scholarship.modules.student.service;

import com.scholarship.common.utils.CommonUtil;
import com.scholarship.modules.login.entity.User;
import com.scholarship.modules.login.mapper.LUserMapper;
import com.scholarship.modules.student.dto.*;
import com.scholarship.modules.student.dto.applicationDto.*;
import com.scholarship.modules.student.entity.Student;
import com.scholarship.modules.student.exce.*;
import com.scholarship.modules.student.mapper.StudentMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private LUserMapper lUserMapper;

    //解密
    private String decode(String encodeStr) {
        String decodeStr;
        try {
            decodeStr = new String(Base64.getDecoder().decode(encodeStr), "utf-8");
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("decode error!!!!!!!!!!!!!!!!");
            return "";
        }
        return decodeStr;
    }

    //加密
    private String encode(String str) {
        String encodeStr;
        try {
            encodeStr = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("encode error!!!!!!!!!1");
            return "";
        }
        return encodeStr;
    }

    /**
     * 获取学生基本信息
     * @param userId
     * @return studentInfoDto
     */
    public StudentInfoDto getStudentInfo(String userId) throws Exception{
        Student userInfo = studentMapper.getStudentByUserId(userId);
        if (userInfo == null) {
            throw new UserException("用户信息有误或不存在");
        }
        if(StringUtils.isNotBlank(userInfo.getIdCard())) {
            userInfo.setIdCard(new String(Base64.getDecoder().decode(userInfo.getIdCard()), "utf-8"));
        }
        if(StringUtils.isNotBlank(userInfo.getBankCard())) {
            userInfo.setBankCard(new String(Base64.getDecoder().decode(userInfo.getBankCard()), "utf-8"));
        }
        if(StringUtils.isNotBlank(userInfo.getPhone())) {
            userInfo.setPhone(new String(Base64.getDecoder().decode(userInfo.getPhone()), "utf-8"));
        }
        if(StringUtils.isNotBlank(userInfo.getEmail())) {
            userInfo.setEmail(new String(Base64.getDecoder().decode(userInfo.getEmail()), "utf-8"));
        }
        StudentInfoDto studentInfoDto = new StudentInfoDto(userInfo.getName(), userInfo.getUserId(), userInfo.getIdCard(), userInfo.getBankCard(), userInfo.getPhone(), userInfo.getEmail());
        return studentInfoDto;
    }

    /**
     * 获取学生专业信息
     * @param userId
     * @return majorInfoDto
     */
    public MajorInfoDto getStudentMajorInfo(String userId) throws Exception{
        MajorInfoDto majorInfoDto = studentMapper.getStudentMajorInfo(userId);
        if (majorInfoDto == null)
            throw  new UserException("对应用户不存在");
        return majorInfoDto;
    }

    /*
     * 更新学生密码
     * 返回值0表示密码错误，1表示更新失败，2表示成功
     */
    public void updateStudentPasswordInfo(StudentPasswordDto studentPassword) throws Exception{
        //检查原密码是否正确
        String userId = studentPassword.getUserId();
//        String user_pwd = studentMapper.getStudentPasswordById(studentPassword.getUserId());
//        User user = loginMapper.getUserByUserId(userId);
        User user = lUserMapper.getUserByUserId(userId);

        String user_pwd = user.getPassword();
        String userOriginalPwd = CommonUtil.encryptPassword(studentPassword.getOriginalPassword(),userId);
        if (user_pwd.equals(userOriginalPwd) == false) {
            throw new PwdException("原密码错误");
        }
        //存储新密码
        String userNewPwd = CommonUtil.encryptPassword(studentPassword.getNewPassword(),userId);
        studentPassword.setNewPassword(userNewPwd);
        int ret = studentMapper.updateStudentPassword(studentPassword);
        if (ret < 1)
            throw new UpdateSQLException("存储密码时出错");
    }

    /*
     * 首次登入修改密码
     * */
    public void updateStudentPwdWhenFirstLogin(String userId, String pwd) throws Exception{
//        User user = loginMapper.getUserByUserId(userId);
        User user = lUserMapper.getUserByUserId(userId);
        if (user == null) {
            throw new UserException("该用户不存在");
        }

        String userNewPwd = CommonUtil.encryptPassword(pwd,userId);
        StudentPasswordDto pwdDto = new StudentPasswordDto();
        pwdDto.setNewPassword(userNewPwd);
        pwdDto.setUserId(userId);
        int ret = studentMapper.updateStudentPassword(pwdDto);
        if (ret < 1) {
            throw new UpdateSQLException("存储用户密码失败");
        }
    }

    /*
     * 更新学生的基本信息
     * 返回值0表示失败，1表示成功
     */
    public void updateStudentBaseInfo(StudentChangeInfoDto stuInfo) throws Exception{
        //利用传来的数据构造Student对象
        Student student = new Student();
        String encodeEmail = encode(stuInfo.getEmail());
        student.setEmail(encodeEmail);
        student.setUserId(stuInfo.getUserId());
        student.setBankCard(encode(stuInfo.getBankCard()));
        student.setIdCard(encode(stuInfo.getIdCard()));
        student.setPhone(encode(stuInfo.getPhone()));

        List<String> userIdList = studentMapper.getUserIdByEmail(encodeEmail);
        if (userIdList.size() > 1) {
            throw new ErrorException("数据库有误，包含了多个重复邮箱的数据");
        }
        else if(userIdList.size() == 1) {
            if (student.getUserId().equals(userIdList.get(0)) == false) {
                throw new GetSQLException("该邮箱已存在");
            }
        }

        int ret = studentMapper.updateStudentBaseInfo(student);
        if (ret < 1)
            throw new UpdateSQLException("数据库存储数据出错");
    }

    //检测学生是否首次登入
    public Boolean isFirstLogin(String userId) throws Exception {
        String stuEmail = "";
        try {
            stuEmail = studentMapper.getStudentEmail(userId);
            if (stuEmail == null || "".equals(stuEmail))
                return true;
            return false;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new Exception("未知错误");
        }
    }

    /*------------------------新旧分割线--------------------*/

    public List<Student> listStudent() {
        return studentMapper.getAllStudent();
    }

    /*
    * 获取奖学金申请表基本信息
    */
    public ApplicationBaseInfoDto getApplicationBaseInfo(String userId) {
        ApplicationBaseInfoDto applicationBaseInfoDto = studentMapper.getApplicationBaseInfo(userId);
        return applicationBaseInfoDto;
    }
}
